package com.banyuan.课堂练习.IO流;

import java.io.*;

/*
 * 将一个文件按照输入数字平均分割
 * */
public class Ex4 {
    public static void main(String[] args) {
        method("aaa.txt", 5);
    }

    public static void method(String fileName, int n) {
        File file = new File(fileName);
        long i = file.length();
        System.out.println(i);
        long avg = i / n;
        byte[] arr = new byte[8];
        //生成i个缓冲字节流
        for (int j = 0; j < n; j++) {
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName.substring(0, fileName.lastIndexOf(".")) + "_" + (j + 1) + fileName.substring(fileName.indexOf("."))))) {
                //当最后一次时rest的初始值为最后剩下的数；
                long rest = j == n - 1 ? i - j * avg : avg;
                while (rest > 0) {
                    bis.skip(j * avg);
                    long len = bis.read(arr);
                    bos.write(arr, 0, (int) Math.min(len, rest));
                    rest -= len;
                    bos.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
